
package com.probiz.estore.core.util;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.engine.query.HQLQueryPlan;
import org.hibernate.hql.QueryTranslator;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.impl.SessionImpl;
import org.springframework.util.Assert;
public class HibernateUtils {
	/**
	 * @param hql只支持单条Hql,不支持"(),"分隔表示多条hql
	 * @param session
	 * @return
	 */
	public static String hqlToSql(String hql,Session session){
		SessionImpl sessionImpl=(SessionImpl)session;
		SessionFactoryImpl sessionFactoryImpl=(SessionFactoryImpl)sessionImpl.getFactory();
		HQLQueryPlan hqlQueryPlan=sessionFactoryImpl.getQueryPlanCache().getHQLQueryPlan(hql, false, sessionImpl.getEnabledFilters());
		QueryTranslator translators[]=hqlQueryPlan.getTranslators();
		if(translators.length>0){
			return translators[0].getSQLString();
		}
		return null;
	}
	/**
	 * 添加条件到hql中
	 * @param hql
	 * @param operator 操作子，如 and or
	 * @param clause  子句
	 * @return
	 */
	public static String appendWhereAndClauseToHql(String hql, String operator,String clause ){
		String upperHql = hql.toUpperCase();
		int idxSelect = upperHql.indexOf("SELECT ");
		int idxFrom = upperHql.indexOf("FROM ");
		int idxWhere = upperHql.indexOf(" WHERE ");
		int idxOrderBy = upperHql.indexOf(" ORDER BY ");

		String selectClause="";
		String fromClause="";
		String whereClause="";
		String orderByClause="";
		
		if (idxSelect >= 0) {
			selectClause = hql.substring(idxSelect, idxFrom);
		}

		int idxEndOfFrom = (idxWhere > 0) ? idxWhere : (idxOrderBy > 0 ? idxOrderBy : hql.length());
		fromClause = hql.substring(idxFrom, idxEndOfFrom);

		if (idxWhere > 0) {
			whereClause = hql.substring(idxWhere, idxOrderBy > 0 ? idxOrderBy : hql.length());
		}

		if (idxOrderBy > 0) {
			orderByClause = hql.substring(idxOrderBy , hql.length());
		}
		if(StringUtils.isNotBlank(whereClause)){
			whereClause +=  operator + " " + clause;
		}else{
			whereClause  = "where" + clause;
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append(selectClause).append(fromClause).append(whereClause).append(orderByClause);
		
		return buffer.toString();
		
	}
	
}
